package com.zzl.admin.controller.web;

import com.zzl.admin.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * Description：登录Controller
 * Created by 朱正磊 on 2019-03-25 17:07
 */
@Slf4j
@Controller
public class LoginController extends BaseController {

    /**
     * description：请求访问登录页面
     * user 朱正磊
     * time 2019-03-26 14:09
     * @return 返回模型视图（登录页面）
     */
    @GetMapping("/admin/login")
    public ModelAndView login() {
        return new ModelAndView("admin/login");
    }

    /**
     * description：请求登录
     * user 朱正磊
     * time 2019-03-26 14:47
     * @param username 用户名
     * @param password 密码
     * @param map 响应信息
     * @return 登录成功，重定向到index页面；登录失败，还是停留在登录页面。
     */
    @PostMapping("/admin/login")
    public ModelAndView login(String username, String password, Map<String, Object> map) {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            return new ModelAndView("redirect:/admin/index");
        } catch (AuthenticationException e) {
            String message = e.getMessage();
            map.put("message", message);
            log.error("【登录异常】异常信息：{}", message);
        }
        return new ModelAndView("admin/login", map);
    }

    /**
     * description：注销登录
     * user 朱正磊
     * time 2019-03-26 14:54
     * @return 注销成功，重定向到登录页面。
     */
    @GetMapping("/admin/logout")
    public ModelAndView logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new ModelAndView("redirect:/admin/login");
    }

}
